package com.ruoyi.file.service;

import com.ruoyi.common.core.exception.ServiceException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.ruoyi.file.utils.FileUploadUtils;

import java.io.File;

/**
 * 本地文件存储
 *
 * @author ruoyi
 */
@Primary
@Service
public class LocalSysFileServiceImpl implements ISysFileService {
    /**
     * 资源映射路径 前缀
     */
    @Value("${file.prefix}")
    public String localFilePrefix;

    /**
     * 域名或本机访问地址
     */
    @Value("${file.domain}")
    public String domain;

    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${file.path}")
    private String localFilePath;

    /**
     * 本地文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file, String fileNames) throws Exception {
        String name = FileUploadUtils.upload(localFilePath, file, fileNames);
        String url = localFilePrefix + name;
        System.out.println("nacos配置地址：" + domain);
        System.out.println("上传地址：" + url);
        return url;
    }

    @Override
    public Boolean delte(String[] urls) {
        if (urls == null || urls.length == 0) {
            throw new ServiceException("删除的文件不能为空");
        }
        for (String url : urls) {
            String[] split = url.split("/");
            String fileName = split[split.length - 1];
            String[] names = fileName.split("\\.")[0].split("_");
            String name = names[names.length - 1];
            String path = parseData(name);
            String deleteName = localFilePath + File.separator + path + File.separator + fileName;
            File file = new File(deleteName);
            if (file.isFile() && file.exists()) {
                file.delete();
            }
        }
        return Boolean.TRUE;
    }

    public static String parseData(String input) {
        return input.substring(0, 4) + File.separator + input.substring(4, 6) + File.separator + input.substring(6, 8);
    }
}
